<template>
  <el-scrollbar 
    ref="scrollbarRef" 
    height="75vh" 
    class="infinite-scroll-wrapper" 
    @scroll="handleScroll"
  >
    <!-- 空状态 -->
    <div v-if="showEmpty" class="empty-tip">
      <slot name="empty">
        <el-empty :description="my_posts ? '你还没有发布过帖子' : '暂时没有相关内容'"/>
      </slot>
    </div>

    <!-- 帖子列表 -->
    <ul v-else class="infinite-list">
      <li 
        v-for="post in posts" 
        :key="post.post_id" 
        class="list-item"
      >
        <post-card 
          :postId="post.post_id"
          :title="post.title"
          :content="post.content"
          :view_count="post.view_count"
          :like_count="post.like_count"
          :created_at="post.created_at"
          :username="post.username"
          :my_posts="my_posts"
          @delete-success="handleDeleteSuccess"
        />
      </li>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-tip">
        <el-icon class="loading-icon">
          <Loading />
        </el-icon>
        <span>正在加载...</span>
      </div>

      <!-- 无更多数据 -->
      <div v-if="noMore" class="no-more">━━ 已经到底啦 ━━</div>
    </ul>
  </el-scrollbar>
</template>

<script lang="ts" setup>
import { ref, computed, watch, onMounted, onActivated, nextTick } from 'vue'
import { ElScrollbar, ElIcon, ElEmpty } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import PostCard from '@/components/card/index.vue'
import { onBeforeRouteLeave } from 'vue-router'
import { postsAPI } from '@/api/posts'
import { useAuthStore } from '@/stores/authStore'
import { storeToRefs } from 'pinia'

const props = defineProps({
  my_posts: {
    type: Boolean,
    default: false
  }
})

// 认证存储
const authStore = useAuthStore()
const { user } = storeToRefs(authStore)

// 组件状态
const posts = ref<any[]>([])
const cursor = ref<number | null>(null)
const hasMore = ref(true)
const loading = ref(false)
const loadingLock = ref(false)
const pageSize = 10

// 计算属性
const noMore = computed(() => !hasMore.value)
const showEmpty = computed(() => !loading.value && posts.value.length === 0)

// 滚动容器引用
const scrollbarRef = ref<InstanceType<typeof ElScrollbar> | null>(null)
const scrollbarWrapRef = ref<HTMLElement | null>(null)
const rememberScroll = ref(0)

// 初始化滚动容器引用
const initScrollRef = async (retry = 0) => {
  await nextTick()
  if (scrollbarRef.value?.wrapRef) {
    scrollbarWrapRef.value = scrollbarRef.value.wrapRef
  } else if (retry < 3) {
    setTimeout(() => initScrollRef(retry + 1), 100)
  }
}

// 数据加载
const load = async () => {
  if (loadingLock.value || !hasMore.value) return

  loadingLock.value = true
  loading.value = true

  try {
    const authorId = props.my_posts ? user.value?.userId : null
    const res = await postsAPI.getPostPaginated(
      cursor.value,
      pageSize,
      authorId
    )

    posts.value = [...posts.value, ...res.data.items]
    cursor.value = res.data.next_cursor
    hasMore.value = res.data.has_more
  } catch (error) {
    console.error('加载失败:', error)
    hasMore.value = false
  } finally {
    loading.value = false
    loadingLock.value = false
  }
}

// 重置状态
const resetState = () => {
  posts.value = []
  cursor.value = null
  hasMore.value = true
}

// 滚动处理
const handleScroll = ({ scrollTop }: { scrollTop: number }) => {
  const container = scrollbarWrapRef.value
  if (!container) return

  const { clientHeight, scrollHeight } = container
  const isBottom = scrollHeight - (scrollTop + clientHeight) <= 100

  if (isBottom && !loading.value && hasMore.value) {
    load()
  }
}

const handleDeleteSuccess = (deletedId) => {
  // 更新列表数据
  posts.value = posts.value.filter(post => post.post_id !== deletedId)
}

// 监听模式变化
watch(() => props.my_posts, () => {
  resetState()
  load()
})

// 生命周期
onMounted(async () => {
  await initScrollRef()
  load()
})

onActivated(async () => {
  await initScrollRef()
  if (scrollbarWrapRef.value) {
    scrollbarWrapRef.value.scrollTop = rememberScroll.value
  }
})

onBeforeRouteLeave(() => {
  if (scrollbarWrapRef.value) {
    rememberScroll.value = scrollbarWrapRef.value.scrollTop
  }
})
</script>

<style scoped>
.infinite-scroll-wrapper {
  max-width: 800px;
  margin: 0 auto;
}

.infinite-list {
  padding: 16px 0;
  list-style: none;
}

.list-item {
  margin-bottom: 12px;
  padding: 0 12px;
}

.empty-tip {
  padding: 40px 0;
}

.loading-tip {
  text-align: center;
  padding: 16px 0;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 0.9em;
}

.loading-icon {
  animation: rotating 1.2s linear infinite;
}

.no-more {
  text-align: center;
  padding: 24px 0;
  color: var(--el-text-color-secondary);
  font-size: 0.9em;
  position: relative;
  margin: 20px 0;
}

.no-more::before {
  content: '';
  position: absolute;
  left: 10%;
  right: 10%;
  top: 0;
  height: 1px;
  background: var(--el-border-color);
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>